#-----------------------
# Let's do some matching
#-----------------------

# Set up
rm(list=ls())
setwd("C:/RWORKING/GAIN")
source("gaintools.R")
library(Matching)

# Read our data, set our comprehensive output variable
data = as.matrix(read.table("C:/data/gain/gain-variables.txt", header=TRUE))
Y = data[,1]
D = data[,2]

# create new variable to signify 0=control, 1=human capital, 2=work first
D.type = data[,2]
workFirst.logical = (data[,3] == 2 & D.type == 1)
D.type[workFirst.logical] = 2

# build subsets for LA county, calculate ATE
LA.index = data[,3]
LA.logical = (LA.index == 6)

Y.LA = subset(Y, LA.logical)
D.LA = subset(data[,2], LA.logical)

X.LA = subset(data[,4:ncol(data)], LA.logical)

Y.LA.D1 = subset(Y.LA, (D.LA == 1))
Y.LA.D0 = subset(Y.LA, (D.LA == 0))

ATE.LA = (mean(Y.LA.D1) - mean(Y.LA.D0))/mean(Y.LA.D0)

# create a matrix of mean descriptive statistics
descript.stats = data.frame(matrix(nrow=ncol(data), ncol=3))
for(i in 1:ncol(data)) {
  overall = data[,i]
  treated = subset(data[,i], D == 1)
  untreated = subset(data[,i], D == 0)
  descript.stats[i,1] = mean(overall)
  descript.stats[i,2] = mean(treated)
  descript.stats[i,3] = mean(untreated)
}

# Effect of Workfirst  (D.type == 0 for control, D.type == 2 for treatment)
idx.workFirst = (D.type != 1)
Y.workFirst = data[idx.workFirst, 1]
D.workFirst = data[idx.workFirst, 2]
X.workFirst = data[idx.workFirst, 4:ncol(data)]

P.workFirst = glm(D.workFirst ~ X.workFirst, family=binomial)$fitted

#ATE.workFirst = Match(Y=Y.workFirst, Tr=D.workFirst, X=P.workFirst)$est

# Effect of Human Capital  (D.type == 0 for control, D.type == 1 for treatment)
idx.humanCap = (D.type != 2)
Y.humanCap = data[idx.humanCap,1]
D.humanCap = data[idx.humanCap,2]
X.humanCap = data[idx.humanCap,4:ncol(data)]

P.humanCap = glm(D.humanCap ~ X.humanCap, family=binomial)$fitted

#ATE.humanCap = Match(Y=Y.humanCap, Tr=D.humanCap, X=P.humanCap)$est
